package com.zyk.grate_offer.class05;

import com.zyk.leetcode.TreeNode;

/**
 * @author zhangsan
 * @date 2021/5/6 16:28
 */
public class Code01_ConvertTree {


    // 树的后序遍历结果 arr, 转换为原先的树
    public static TreeNode posToTree(int[] arr) {
        int N = arr.length;
        TreeNode root = new TreeNode(arr[N - 1]);
        for (int i = N - 2; i >= 0; i--) {
            root = add(root, arr[i]);
        }
        return root;
    }

    public static TreeNode add(TreeNode root, int n) {
        if (root == null) {
            return new TreeNode(n);
        }
        if (n > root.val) {
            root.right = add(root.right, n);
        } else {
            root.left = add(root.left, n);
        }
        return root;
    }

    public static void inPrint(TreeNode root) {
        if (root == null) return;
        inPrint(root.left);
        System.out.print(root.val + " - ");
        inPrint(root.right);
    }


    public static void main(String[] args) {
        int[] arr = {1, 4, 5, 3, 7, 10, 8, 6};
        TreeNode root = posToTree(arr);
        inPrint(root);
        System.out.println();
    }

}
